<template>
  <!-- 新增/修改菜单的弹窗 -->
  <el-drawer v-model="dialogVisible" size="60%" @close="closeDialog(deptFormRef)" class="custom-drawer">
    <template #title>
      <span class="flex items-center">
        <el-icon class="mr-1" :size="20" color="var(--el-color-primary)"><DocumentAdd /></el-icon>
        {{ dialogTitle }}
      </span>
    </template>
    <el-form ref="deptFormRef" :model="formData" :rules="rules" :label-width="formLabelWidth" :disabled="setRoleDisabled">
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="归属部门" prop="deptId">
            <el-tree-select
              v-model="formData.deptId"
              :data="deptTreeData"
              placeholder="请选择归属部门"
              check-strictly
              :render-after-expand="false"
              :props="{ value: 'id', label: 'deptName', children: 'children' }"
              clearable
            >
            </el-tree-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="formData.username" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="用户昵称" prop="nickname">
            <el-input v-model="formData.nickname" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="formData.phone" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="用户邮箱" prop="email">
            <el-input v-model="formData.email" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户性别" prop="sex">
            <el-select v-model="formData.sex">
              <el-option v-for="(item, key) in SEX_STATUS" :key="key" :label="item" :value="key" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="用户姓名" prop="name">
            <el-input v-model="formData.name" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户工号" prop="jobNumber">
            <el-input v-model="formData.jobNumber" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="24">
          <el-form-item label="所在岗位" prop="post">
            <el-select v-model="formData.post" clearable filterable multiple>
              <el-option
                v-for="(item, index) in postList.filter(i => i.id !== undefined)"
                :key="index"
                :label="item.name"
                :value="item.id ?? ''"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="24">
          <el-form-item label="备注信息" prop="remark">
            <el-input v-model="formData.remark" type="textarea" :rows="6" resize="none" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-descriptions title="用户分配角色" class="custom-desc mt-6"></el-descriptions>
    <el-divider class="desc-divider"></el-divider>
    <el-table :data="roleList" row-key="id" @selection-change="handleSelectionChange">
      <el-table-column type="selection" reserve-selection width="55" />
      <el-table-column label="序号" prop="id"></el-table-column>
      <el-table-column label="角色名称" prop="roleName"></el-table-column>
      <el-table-column label="角色编码" prop="roleCode"></el-table-column>
    </el-table>
    <template #footer>
      <el-button :loading="submitLoading" @click="closeDialog(deptFormRef)"> 取消</el-button>
      <el-button type="primary" :loading="submitLoading" @click="handleSave(deptFormRef)"> 确认</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { Dept, Post, Role, User } from "@/api/interface";
import { getDeptTree } from "@/api/modules/dept";
import { SEX_STATUS } from "@/enums";
import { addUser, editUser } from "@/api/modules/user";
import { getPostList } from "@/api/modules/post";

defineOptions({
  name: "UserAdd"
});

const emits = defineEmits(["close"]);
const formLabelWidth = "100px";
const dialogTitle = ref("新增用户");
const dialogVisible = ref(false);
const setRoleDisabled = ref(false);
const deptFormRef = ref<FormInstance>();
const formData = reactive<User.IUser>({
  deptId: undefined,
  username: "",
  nickname: "",
  phone: "",
  email: "",
  roles: []
});

const submitLoading = ref(false);

const rules = ref<FormRules<User.IUser>>({
  deptId: [{ required: true, message: "请选择归属部门", trigger: "change" }],
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  nickname: [{ required: true, message: "请输入用户昵称", trigger: "blur" }],
  email: [{ required: true, type: "email", message: "请输入正确的邮箱地址", trigger: "blur" }],
  phone: [{ required: true, pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" }]
});

const deptTreeData = ref<Dept.IDept[]>([]);
const roleList = ref<Role.IRole[]>([]);
const postList = ref<Post.IPost[]>([]);

const openDialog = async (type = "add", item: any = {}) => {
  dialogTitle.value = type === "edit" ? "修改用户" : "新增用户";
  deptFormRef.value?.resetFields();

  if (type === "edit") {
    formData.id = item.id;
    formData.deptId = item.dept?.id;
    formData.username = item.username;
    formData.nickname = item.nickname;
    formData.phone = item.phoneNumber;
    formData.email = item.email;
    formData.roles = item.roles?.map((role: Role.IRole) => role.id);
    formData.post = item.posts?.map((post: Post.IPost) => post.id);
    formData.remark = item.remark;
    formData.name = item.name;
    formData.jobNumber = item.jobNumber;
    item.setRole && (setRoleDisabled.value = true);
  }
  dialogVisible.value = true;
  await getAllDept();
  await getAllPost();
};

const getAllDept = async () => {
  const { data } = await getDeptTree();
  deptTreeData.value = data;
};

const getAllPost = async () => {
  const {
    data: { records }
  } = await getPostList({ current: 1, size: 100 });
  postList.value = records;
};

const handleSave = (formRef: FormInstance | undefined) => {
  if (!formRef) return;
  submitLoading.value = true;
  formRef.validate(async (valid: boolean) => {
    if (valid) {
      try {
        const saveURL = formData.id ? editUser : addUser;
        await saveURL(formData);
        ElMessage.success("保存成功");
        closeDialog(formRef);
        submitLoading.value = false;
      } catch (e) {
        submitLoading.value = false;
      }
    } else {
      submitLoading.value = false;
    }
  });
};

const handleSelectionChange = selection => {
  formData.roles = selection.map(item => item.id);
};

const closeDialog = (formRef: FormInstance | undefined) => {
  if (!formRef) return;
  formData.id = undefined;
  formRef.resetFields();
  dialogVisible.value = false;
  setRoleDisabled.value = false;
  emits("close");
};
defineExpose({
  openDialog
});
</script>

<style scoped lang="scss">
.desc-divider {
  margin-top: 0 !important;
  margin-bottom: 20px !important;
}
:deep(.el-descriptions__title) {
  color: var(--el-color-primary);
}
</style>
